package com.myproject.myblogserver.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * <p>
 * JWT 工具类
 * </p>
 *
 * @author jiangweike
 * @since 2025-2-9
 */
public class JwtUtil {

    private static final String SECRET_KEY = "JiangWeike"; // 替换为你的密钥
    public static final long ACCESS_TOKEN_EXPIRATION_TIME = 60 * 60 * 1000; // Access Token 有效期 60 分钟
    private static final long REFRESH_TOKEN_EXPIRATION_TIME = 7 * 24 * 60 * 60 * 1000; // Refresh Token 有效期 7 天

    /**
     * 生成 Access Token
     */
    public static String generateAccessToken(String userId) {
        return JWT.create()
                .withSubject(userId)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TIME))
                .sign(Algorithm.HMAC512(SECRET_KEY));
    }

    /**
     * 生成 Refresh Token
     */
    public static String generateRefreshToken(String userId) {
        return JWT.create()
                .withSubject(userId)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRATION_TIME))
                .sign(Algorithm.HMAC512(SECRET_KEY));
    }

    /**
     * 验证 Token 是否有效
     */
    public static boolean validateToken(String token) {
        try {
            JWT.require(Algorithm.HMAC512(SECRET_KEY)).build().verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 获取 Token 中的用户Id
     */
    public static String getUserIdFromToken(String token) {
        if (token.equals("noToken")) {
            return "-1";
        }
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getSubject();
    }

    /**
     * 获取 Token 中的用户Id
     */
    public static Long extractUserIdFromAuthHeader(String authHeader) {
        return Long.parseLong(JwtUtil.getUserIdFromToken(TokenUtil.extractToken(authHeader)));
    }
}